//
//  SXTabBar.m
//  Weibo1
//
//  自定义TabBar控件
//

#import "SXTabBar.h"

@interface SXTabBar()
@property (nonatomic, weak) UIButton *plusBtn;  //底部+号按钮

@end

@implementation SXTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        if (!iOS7) {
            self.backgroundImage = [UIImage imageWithName:@"tabbar_background"];
        }
        self.selectionIndicatorImage = [UIImage imageWithName:@"navigationbar_button_background"];
        [self addPlusBtn];
    }
    return self;
}


- (void)addPlusBtn
{
    
    UIButton *plusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    // backgroundImage
    [plusBtn setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button"] forState:UIControlStateNormal];
    [plusBtn setBackgroundImage:[UIImage imageWithName:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
    // image
    [plusBtn setImage:[UIImage imageWithName:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
    [plusBtn setImage:[UIImage imageWithName:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
    // click event
     [plusBtn addTarget:self action:@selector(plusBtnClick) forControlEvents:UIControlEventTouchUpInside];
    // addSubview
    [self addSubview:plusBtn];
    //save
    self.plusBtn = plusBtn;
}


- (void)plusBtnClick
{
    SXLog(@"点击了发微博按钮");
    
    if ([self.delegate respondsToSelector:@selector(SXTabBarDidClickPlusButton:)]) {
        [self.mydelegate SXTabBarDidClickPlusButton:self];
    }
}


- (void)layoutSubviews {
    
    [super layoutSubviews];
    [self setPlusBtnFrame];
    [self setOtherTabBarButtonFrame];
}


- (void)setPlusBtnFrame {
    
    self.plusBtn.size = self.plusBtn.currentBackgroundImage.size;
    self.plusBtn.center = CGPointMake(self.width * 0.5, self.height * 0.5);
}


- (void)setOtherTabBarButtonFrame {
    
    int index = 0;
    for (UIView *tabBarButton in self.subviews) {
        if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            continue;
        }
        [self setTabBarButtonFrame:tabBarButton atIndex:index];
        index++;
    }
}


- (void)setTabBarButtonFrame:(UIView *)tabBarButton atIndex:(int)index {
    
    CGFloat btnW = self.width / (self.items.count + 1);
    CGFloat btnH = self.height;
    
    if (index >=2) {
        tabBarButton.x = btnW * (index + 1);
    } else {
        tabBarButton.x = btnW *index;
    }
    tabBarButton.y = 0;
    
    // 这里的加1是，加上上面定义的那个加号按钮
    tabBarButton.width = btnW;
    tabBarButton.height = btnH;
}


@end
